package models

import (
	"SSO/tools"
	"time"
)

type Login struct {
	SessionId      string
	UserId         int
	ServiceId      int
	Uid            string
	IsVerify       int   `gorm:"default:0"`
	ExpirationDate int64 `json:"expiration_date"`
}

type Logins struct{}

func (this Logins) GetByUid(uid string) (*Login, error) {
	logins := make([]Login, 0)
	r := tools.GetMysqlDB().Where("uid = ?", uid).Find(&logins)
	if r.Error != nil {
		return nil, r.Error
	}

	if len(logins) == 0 {
		return nil, nil
	}
	return &logins[0], nil
}

func (Logins) GetBySessionId(sessionIdMd5 string) (logins []Login, err error) {
	logins = make([]Login, 0)
	r := tools.GetMysqlDB().Where("session_id = ?", sessionIdMd5).Find(&logins)
	if r.Error != nil {
		return nil, r.Error
	}
	return
}

func (this Logins) Create(sessionId string, userId, serviceId int, uid string, isVerify int, expirationDate int64) error {
	login := Login{
		SessionId:      sessionId,
		UserId:         userId,
		ServiceId:      serviceId,
		Uid:            uid,
		IsVerify:       isVerify,
		ExpirationDate: expirationDate,
	}

	r := tools.GetMysqlDB().Create(&login)

	if r.Error != nil {
		return r.Error
	}

	return nil
}

func (Logins) UpdateIsVerifyByUid(uid string, isVerift int) error {
	r := tools.GetMysqlDB().Model(&Login{}).Where("uid = ?", uid).Update("is_verify", 1)
	if r.Error != nil {
		return r.Error
	}
	return nil
}


func (Logins) DeleteBySessionId(sessionIdMd5 string) error {
	r := tools.GetMysqlDB().Where("session_id = ?", sessionIdMd5).Delete(Login{})

	if r.Error != nil {
		return r.Error
	}
	return nil
}

func (Logins) ClearExpire() error {
	timeUnix := time.Now().Unix() - 86400

	r := tools.GetMysqlDB().Where("expiration_date < ?", timeUnix).Delete(Login{})

	if r.Error != nil {
		return r.Error
	}
	return nil
}



